#include <math.h>
#include "B3_defines.h"
#include "gentone.h"

extern const unsigned char B3_wheel_output_level[];

extern long* wheels[WHEEL_NUM + 1];
extern long wave_len[WHEEL_NUM + 1];

extern long ppos[WHEEL_NUM + 1];
extern long wheel_v_current[WHEEL_NUM + 1];
extern long wheel_v_dest[WHEEL_NUM + 1];
extern keys_t keys1[KEY_NUM + 1];
extern keys_t keys2[KEY_NUM + 1];
extern drawbar_t drawbar1[DRAWBAR_NUM + 1];
extern drawbar_t drawbar2[DRAWBAR_NUM + 1];
extern drawbar_level_t drawbar_level[DRAWBAR_LEVEL_NUM];

#define V_ACCEL 1

void
update_wheel_v() {
	unsigned char i;
	for (i=1; i<=WHEEL_NUM; i++) {
		if (wheel_v_dest[i] - wheel_v_current[i] > V_ACCEL)
			wheel_v_current[i]+= V_ACCEL;
		else if (wheel_v_current[i] - wheel_v_dest[i] > V_ACCEL)
			wheel_v_current[i]-= V_ACCEL;
		else
			wheel_v_current[i] = wheel_v_dest[i];
	}
}

void
gentone(int buf_len, smpl_t *wav_buf) {
	int i;
	unsigned char j;
        long long temp; //for accurate

        for (i = 0; i < buf_len; ++i) {
                temp = 0;
		update_wheel_v();
                for (j = 1;j <= WHEEL_NUM; ++j) {
                        temp += (long long) wheels[j][ppos[j]] * wheel_v_current[j] * B3_wheel_output_level[j];
                        ppos[j] = (ppos[j] + 1) % wave_len[j];
                }
                wav_buf[i] = temp >> 25;  //original 26.
        }
}
